import SalesPlanAPI from '../../../common/api/salesplan/salesplanmain.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";


(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner"><span style='margin:0 auto;margin-top:10px'>请选择业务日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;
    const deliveryTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner"><span style='margin:0 auto;margin-top:10px'>请选择发货日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;
    const addsaleTemplate = doT.template($('#addsale-template').text());
    let _vm, _ownOrgs = [], _stuffInfo = [], _pickerTime, _deliveryTime, savetype,
        custom, saleOrgsinfo, getEntryInfo = [], operaEntry, operaEntryId, nextEntryId = 1, getMainInfo, timer = null, addstyleEntry, edistyleEntry, renderEntryInfo = []
        ;

    $(async function () {
        _vm = new Vue({
            el: "#addsalesplan-form",
            data() {
                return {
                    "saleOrg": {
                        "id": "",
                        "name": ""
                    },
                    "customer": {
                        "id": "",
                        "name": "",
                        "numCode": "",
                        "phoneNum": "",
                        "address": ""
                    },
                    "entries": [
                        {
                            "seq": "",
                            "material": {
                                "id": "",
                                "numCode": "",
                                "name": "",
                                "model": "",
                                "fassistUnit": "",
                                "baseMeasureUnit": ""
                            },
                            "fassistQty": "",
                            "baseQty": "",
                            "remark": ""
                        }
                    ],
                    "bizDate": "",
                    "deliveryDate": "",
                    "shippingType": "",
                    "seller": {
                        "id": "",
                        "name": "",
                        "numCode": ""
                    }
                }
            },
            methods: {
                submit() {
                    savedata()
                }
            },
        });
        await _ediCommand()
        ctlReturn()
        selfAdaption()
        _initCommand()
        _datetimePickerInit()
        _deliveryPickerInit()
        saleOrgs()
        custominfo()
        _initShipping()
        _delSalesEntry()
        _ediSalesEntry()
        _initseller()

        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = () => {
        // 获取分录以上的信息
        getMainInfo = JSON.parse(Utils.GetSessionStorage("mainInfo"))
        if (Utils.IsNotNull(getMainInfo)) {
            _vm.saleOrg = getMainInfo.saleOrg
            _vm.customer = getMainInfo.customer
            _vm.bizDate = getMainInfo.bizDate
            _vm.deliveryDate = getMainInfo.deliveryDate
            _vm.seller = getMainInfo.seller
            _vm.shippingType = getMainInfo.shippingType

        }
        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        if (Utils.IsNotNull(getEntryInfo)) {
            renderEntryInfo = JSON.parse(JSON.stringify(getEntryInfo));
            renderEntryInfo.forEach(item => {
                item.fassistQty = formatQfw(item.fassistQty)
                item.baseQty = formatQfw(item.baseQty)
            })
            $('#salesEntry').empty().append(addsaleTemplate(renderEntryInfo));
        }
        // 获取下一个分录的序号
        if (Utils.IsNotNull(getUrlKey('nextEntryId'))) {
            nextEntryId = getUrlKey('nextEntryId')
        }
        // 点击添加明细按钮
        $('#addSalesEntry').on('click', function () {
            if (Utils.IsNotNull(getUrlKey("id"))) {
                location.href = `../salesplan/salesentry.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}`;
            }
            else {
                location.href = `../salesplan/salesentry.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}`;
            }
            _mainInfo()
        })
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../salesplan/salesplanmain.html?v=${Utils.GetTime()}`;
        });
    }
    // 保存分录以上的信息
    const _mainInfo = () => {
        let _mainInfo = { ...{ saleOrg: _vm.saleOrg }, ...{ customer: _vm.customer }, ...{ seller: _vm.seller }, bizDate: _vm.bizDate, deliveryDate: _vm.deliveryDate, shippingType: _vm.shippingType };
        JSON.stringify(Utils.SetSessionStorage("mainInfo", _mainInfo))
    }
    // 初始化销售组织
    const saleOrgs = async () => {
        // _stuffInfo = await SalesPlanAPI.getUserInfo();
        _stuffInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {}
        _ownOrgs = await SalesPlanAPI.postUserOrgsList();
        SalesPlanAPI.getOrgsListType().then(res => {
            let sale = res.filter(s => s.typeValue == true);
            let obj = _ownOrgs.filter(item => sale.some(item2 => item2.id == item.oId));
            let ownAccount = obj.find(s => s.oId == _stuffInfo.coui);
            $('#saleOrgs').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: "zh-CN",//汉化
                data: obj.map(item => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        text: `${item.oName}(${item.oNumCode})`
                    }
                }),
            });
            //解决字段过长
            $('#saleOrgs').on('change', function () {
                saleOrgsinfo = cutstr($('#select2-saleOrgs-container').text(), 22)
                $('#select2-saleOrgs-container').text(`${saleOrgsinfo}`)
                if (Utils.IsNotNull($('#saleOrgs').select2('data')[0])) {
                    _vm.saleOrg.id = $('#saleOrgs').select2('data')[0].id
                    _vm.saleOrg.name = $('#saleOrgs').select2('data')[0].name
                }
            })
            if (Utils.IsNotNull(getUrlKey("id"))) {
                $("#saleOrgs").val(_vm.saleOrg.id).trigger('change');
                $("#saleOrgs").change()
                $("#saleOrgs").select2({ disabled: true });
                if (!Utils.IsNotNull($('#select2-saleOrgs-container').text())) {
                    $('#select2-saleOrgs-container').text(`${_vm.saleOrg.name}`)
                }
                saleOrgsinfo = cutstr($('#select2-saleOrgs-container').text(), 22)
                $('#select2-saleOrgs-container').text(`${saleOrgsinfo}`)
            }
            else if (Utils.IsNotNull(getMainInfo) && Utils.IsNotNull(getMainInfo.saleOrg.id)) {
                $('#saleOrgs').val(getMainInfo.saleOrg.id).trigger('change');
                $("#saleOrgs").change()
                saleOrgsinfo = cutstr($('#select2-saleOrgs-container').text(), 22)
                $('#select2-saleOrgs-container').text(`${saleOrgsinfo}`)
            }
            else if (Utils.IsNotNull(ownAccount)) {
                $('#saleOrgs').val(ownAccount.oId).trigger('change');
                $("#saleOrgs").change()
            }
            else {
                $('#saleOrgs').val(null).trigger('change');
                $("#saleOrgs").change()
            }
        })
    }
    // 初始化客户信息
    const custominfo = () => {
        //客户初始化
        Select2Page($(`#selCustomerInfos`), `${Utils.CurDomain.MasterDataUrl}/yycustomers/by/q`, (params) => {
            return ({
                SearchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择客户...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`;
            }
        });
        $("#selCustomerInfos").setSelectValue();

        $("#selCustomerInfos").setSelectValue(_vm.customer.id, _vm.customer.name);
        $("#selCustomerInfos").val(_vm.customer.id).trigger('change');
        //解决客户字段过长
        $('#selCustomerInfos').on('change', function () {
            _vm.customer.id = $('#selCustomerInfos').select2('data')[0]?.id
            _vm.customer.numCode = $('#selCustomerInfos').select2('data')[0]?.numCode
            _vm.customer.name = $('#selCustomerInfos').select2('data')[0]?.name
        })

    }
    // 初始化发货类型
    const _initShipping = () => {
        requestDict(DictionaryType.shipping_TYPE).then(res => {
            $('#shippingType').select2({
                placeholder: '请选择发货类型...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            if (Utils.IsNotNull(_vm.shippingType)) {
                $("#shippingType").val(_vm.shippingType).trigger('change');
            }
            else {
                $("#shippingType").val(null).trigger('change');
            }
            $('#shippingType').on('change', function () {
                _vm.shippingType = $('#shippingType').select2('data')[0].id
            })
        });
    }
    // 初始化员工
    const _initseller = async () => {
        let uersInfo = []
        // await SalesPlanAPI.getLoginUserToStaff()
        Select2Page($(`#seller`), `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`, (params) => {
            return ({
                Status: true,
                SearchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择销售员...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`;
            }
        });
        $("#seller").setSelectValue(uersInfo?.id, uersInfo?.name);
        $("#seller").setSelectValue(_vm.seller.id, _vm.seller.name);
        $("#seller").val(_vm.seller.id).trigger('change');

        $('#seller').on('change', function () {
            _vm.seller.id = $('#seller').select2('data')[0]?.id
            _vm.seller.numCode = $('#seller').select2('data')[0]?.numCode
            _vm.seller.name = $('#seller').select2('data')[0]?.name
        })

    }

    //业务日期控件初始化
    const _datetimePickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $("#search-date").picker("open");
            _pickerDate();
        });
        $("#search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _pickerTime = '';
                    _pickerTime = value;
                }
            }
        );
    }
    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#businessTime').val(_pickerTime);
            _vm.bizDate = _pickerTime
        });
    }
    // 业务日期获取当天
    const initCurrentDay = () => {
        let todayDate = moment().format('YYYY-MM-DD')
        $('#businessTime').val(todayDate)
        _vm.bizDate = todayDate
    }

    //发货日期控件初始化
    const _deliveryPickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#delivery-date').on('click', function (e) {
            e.stopPropagation();
            $("#delivery-date").picker("open");
            _deliverypickerDate();
        });
        $("#delivery-date").datetimePicker(
            {
                toolbarTemplate: deliveryTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _deliveryTime = '';
                    _deliveryTime = value;
                }
            }
        );
    }
    //发货日期确认事件
    const _deliverypickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#deliveryDate').val(_deliveryTime);
            _vm.deliveryDate = _deliveryTime
        });
    }
    // 删除分录
    const _delSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            operaEntry = $(this).parents('.report-contents-item-box').attr('id')
            operaEntryId = operaEntry.substr(operaEntry.length - 1, 1)
            deltips()
        })
    }
    // 删除分录提示
    const deltips = () => {
        $.modal({
            autoClose: false,
            title: '删除提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        getEntryInfo.splice(operaEntryId - 1, 1)
                        _initEntry()
                        $.closeModal();
                    }
                }
            ]
        });
    }
    // 编辑分录
    const _ediSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            operaEntry = $(this).parents('.report-contents-item-box').attr('id')
            operaEntryId = operaEntry.substr(operaEntry.length - 1, 1)
            // 
            if (Utils.IsNotNull(getUrlKey("id"))) {
                location.href = `../salesplan/salesentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}`;
            }
            else {
                location.href = `../salesplan/salesentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}&nextEntryId=${nextEntryId}`;
            }
            _mainInfo()
        })
    }

    // 编辑和删除分录后，重新渲染分录
    const _initEntry = () => {
        getEntryInfo.forEach(function (item, index) {
            item.seq = index + 1
        })
        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
        nextEntryId = Number(getEntryInfo.length) + 1
        renderEntryInfo = JSON.parse(JSON.stringify(getEntryInfo));
        renderEntryInfo.forEach(item => {
            item.fassistQty = formatQfw(item.fassistQty)
            item.baseQty = formatQfw(item.baseQty)
        })
        $('#salesEntry').empty().append(addsaleTemplate(renderEntryInfo));
        // addsalesdetai()
    }
    // 编辑操作
    const _ediCommand = async () => {
        if (Utils.IsNotNull(getUrlKey("id"))) {
            $("#informationSubmit").text("保存");
            $("title").text("编辑销售计划");
            if (!Utils.IsNotNull(getUrlKey("nextEntryId"))) {
                await SalesPlanAPI.querySalesInfo(getUrlKey("id")).then(res => {
                    _vm.saleOrg = res.saleOrg
                    _vm.customer = res.customer
                    _vm.bizDate = res.bizDate.split(' ')[0].replace(/\//g, '-')
                    _vm.deliveryDate = res.deliveryDate.split(' ')[0].replace(/\//g, '-')
                    _vm.shippingType = res.shippingType
                    if (Utils.IsNotNull(res.seller)) {
                        _vm.seller = res.seller
                    }
                    res.entries.forEach(item => {
                        delete item.salePlanBillId
                    })
                    getEntryInfo = res.entries
                    _initEntry()
                })
            }
        }
    }
    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull($('#deliveryDate').val())) {
            return $.toptip(`请选择发货日期!`, 'warning');
        }
        if (!Utils.IsNotNull($('#selCustomerInfos').select2('data'))) {
            return $.toptip(`请选择客户!`, 'warning');
        }
        if (!_vm.customer.phoneNum) { return $.toptip('请输入联系方式', 'warning') } else {
            if (!/^1[3456789]\d{9}$/.test(_vm.customer.phoneNum.trim())) {
                return $.toptip('请输入正确的联系方式', 'warning');
            }
        };
        if (!Utils.IsNotNull(getEntryInfo)) {
            return $.toptip(`请添加计划明细!`, 'warning');
        }
        savetips()
    }
    // 保存提示
    const savetips = () => {
        if (Utils.IsNotNull(getUrlKey("id"))) {
            savetype = '修改'
            addstyleEntry = "display:none"
            edistyleEntry = "display:block"
        }
        else {
            savetype = '保存'
            addstyleEntry = "display:block"
            edistyleEntry = "display:none"
        }
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" style="${addstyleEntry}" >是否确认${savetype}该单据并提交？</div>
                        <div class="edientry" style="${edistyleEntry}">是否确认${savetype}并保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        if (Utils.IsNotNull(getEntryInfo)) {
                            let _param = { ...{ entries: getEntryInfo }, ...{ saleOrg: _vm.saleOrg }, ...{ customer: _vm.customer }, ...{ seller: _vm.seller }, bizDate: _vm.bizDate, deliveryDate: _vm.deliveryDate, shippingType: _vm.shippingType, image: "" };
                            if (Utils.IsNotNull(getUrlKey("id"))) {
                                SalesPlanAPI.ediSalesList(getUrlKey("id"), _param).then(res => {
                                    $.toptip('请求成功。', 'success');
                                    location.href = `./salesplanmain.html?v=${Utils.GetTime()} `;
                                })
                            }
                            else {
                                SalesPlanAPI.addSalesList(_param).then(res => {
                                    $.toptip('请求成功。', 'success');
                                    location.href = `./salesplanmain.html?v=${Utils.GetTime()} `;

                                })
                            }
                        }
                    }
                }
            ]
        });
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    const selfAdaption = () => {
        document.addEventListener('touchstart', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        })

        document.addEventListener('touchmove', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        })
        document.addEventListener('touchend', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        })
    }
    // 控制返回按钮，返回的页面
    const ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `./salesplanmain.html?v=${Utils.GetTime()} `;
            });
        }
    }
    // 千分位
    const formatQfw = (num) => {
        var reg = /\d{1,3}(?=(\d{3})+$)/g;
        return (num + '').replace(reg, '$&,');
    }
})(window, document, jQuery)